const fs = require("fs")
const path = require("path")
const axios = require("axios")
const cheerio = require("cheerio")
const baseApi = "https://www.tianqi.com/"

const chinacity = fs.readFileSync(path.join(__dirname, "data/city.json"))
const internationalCity = fs.readFileSync(path.join(__dirname, "data/internationalCity.json"))
const chinacityJson = JSON.parse(chinacity.toString())
const internationalCityJson = JSON.parse(internationalCity.toString())

//获取国内城市、国际城市网页连接
let getCityUrl = cityName => {
    let city = chinacityJson[cityName]
    if (city === undefined) {
        return baseApi + internationalCityJson[cityName]
    }
    return baseApi + city
}
/**
 * 获取国内未来几天的天气
 * @param {*} url 
 * @returns promise
 */
let getFutuerWeather = url => {
    return new Promise((resovle, reject) => {
        axios.get(url + "15/").then(resp => {
            resovle(resp)
        }).catch(err => reject(err))
    })
}


/**
 * 通过http地址获取天气json信息
 * 依赖data内的数据
 * 示例
 * getWeather("广安").then(data=>{console.log(data)})
 * @param {*} cityname 城市名称
 * @returns promise
 */
let getWeather = cityname => {
    let url = getCityUrl(cityname)
    return new Promise((resovle, reject) => {
        axios.get(url).then(resp => {
            let $ = cheerio.load(resp.data)
            let weather = $(".weather")

            let data = {};
            if (!url.endsWith("html")) {
                console.log("国内天气查询：" + cityname)
                getFutuerWeather(url).then(value => {
                    let $f = cheerio.load(value.data)
                    let futureWeather = []
                    $f(".weaul li").each((i, item) => {
                        futureWeather.push({
                            date: $f(item).find(".fl").text(),
                            day: $f(item).find(".fr").text(),
                            weatherCondition: $f(item).find(".weaul_z").eq(0).text(),
                            temperatureRange: $f(item).find(".weaul_z").eq(1).text(),
                        })
                    })

                    //爬取国内生活指数
                    var lifeData = []
                    $(".weather_life300 ul li").each((index, item) => {
                        lifeData.push({
                            event: $(item).find("b").text(),
                            cando: $(item).find("p").text()
                        })
                    })
                    data = {
                        city: $(".name h2").text(),
                        type: "国内城市",
                        date: $(".week").eq(0).text(),
                        temperature: weather.find(".now b").text() + "℃",//度数
                        weatherCondition: weather.find("span b").text(),//阴晴
                        temperatureRange: weather.find("span").html().split(">")[2],//度数区间
                        airQuality: $(".kongqi h5").text(),//空气质量
                        pm: $(".kongqi h6").text(),//pm
                        sunriseTime: $(".kongqi span").html().split('<br>')[0],//日出时间
                        sunsetTime: $(".kongqi span").html().split('<br>')[1],
                        humidity: $(".shidu b").eq(0).html().split("：")[1],//湿度
                        windDirection: $(".shidu b").eq(1).html().split("：")[1],//风向
                        ultravioletRays: $(".shidu b").eq(2).html().split("：")[1],//紫外线
                        lifeData,//生活指数
                        futureWeather,//未来天气
                    }
                    resovle(data)
                })
            } else {
                console.log("国际天气查询：" + cityname)
                let futureWeather = []
                $(".tianshu li").each((i, item) => {
                    futureWeather.push({
                        date: $(item).find(".jihao").text(),
                        day: $(item).find("strong").text(),
                        weatherCondition: $(item).find(".duoyun").text(),
                        temperatureRange: $(item).find(".du").text(),
                    })
                })
                data = {
                    city: $("h1.fl").text().replace("天气预报", ""),
                    type: "国际城市",
                    date: $(".national_date span").text(),
                    temperature: $(".xiangdui strong").text() + "℃",//度数
                    weatherCondition: $(".national_weather span").eq(0).text(),//阴晴
                    temperatureRange: $(".national_weather span").eq(1).text(),//度数区间
                    airQuality: null,//空气质量
                    pm: null,//pm
                    sunriseTime: null,//日出时间
                    sunsetTime: null,
                    humidity: $(".fengxiang .lev1 span").eq(2).text(),//湿度
                    windDirection: $(".fengxiang div span span").eq(2).text(),//风向
                    ultravioletRays: $(".fengxiang div span").last().text(),//紫外线
                    lifeData: null,//生活指数
                    futureWeather,//未来天气
                }
                resovle(data)
            }
        }).catch(err => reject(err))
    })
}

/**
 * 后添加的模糊查询 但是只能查询国内
 * 为了不改动原来的代码导致bug
 * 宁可冗余
 * @param {*} url 
 * @returns 
 */
let getWeatherByUrl = url => {
    return new Promise((resovle, reject) => {
        axios.get(url).then(resp => {
            let $ = cheerio.load(resp.data)
            let weather = $(".weather")
            let data = {};
            console.log("国内天气查询,模糊查询")
            getFutuerWeather(url).then(value => {
                let $f = cheerio.load(value.data)
                let futureWeather = []
                $f(".weaul li").each((i, item) => {
                    futureWeather.push({
                        date: $f(item).find(".fl").text(),
                        day: $f(item).find(".fr").text(),
                        weatherCondition: $f(item).find(".weaul_z").eq(0).text(),
                        temperatureRange: $f(item).find(".weaul_z").eq(1).text(),
                    })
                })

                //爬取国内生活指数
                var lifeData = []
                $(".weather_life300 ul li").each((index, item) => {
                    lifeData.push({
                        event: $(item).find("b").text(),
                        cando: $(item).find("p").text()
                    })
                })
                data = {
                    city: $(".name h2").text(),
                    type: "国内城市",
                    date: $(".week").eq(0).text(),
                    temperature: weather.find(".now b").text() + "℃",//度数
                    weatherCondition: weather.find("span b").text(),//阴晴
                    temperatureRange: weather.find("span").html().split(">")[2],//度数区间
                    airQuality: $(".kongqi h5").text(),//空气质量
                    pm: $(".kongqi h6").text(),//pm
                    sunriseTime: $(".kongqi span").html().split('<br>')[0],//日出时间
                    sunsetTime: $(".kongqi span").html().split('<br>')[1],
                    humidity: $(".shidu b").eq(0).html().split("：")[1],//湿度
                    windDirection: $(".shidu b").eq(1).html().split("：")[1],//风向
                    ultravioletRays: $(".shidu b").eq(2).html().split("：")[1],//紫外线
                    lifeData,//生活指数
                    futureWeather,//未来天气
                }
                resovle(data)
                console.log(data)
            })
        }).catch(err => reject(err))
    })
}

let getCityInfoByLike = (likeStr) => {
    return new Promise((resovle, reject) => {
        axios.get(baseApi + "tianqi/ctiy?keyword=" + likeStr)
            .then(resp => {
                resovle(resp.data)
            }).catch(err => {
                reject(err)
            })
    })
}

module.exports = {
    getWeather,
    getWeatherByUrl,
    getCityInfoByLike
}